home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 2844 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.8 KB

  1. Path: news.halcyon.com!usenet
  2. From: normanb@halcyon.com (Norm Bryar)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: casting virtual base classpointer to derived
  5. Date: Sat, 20 Jan 1996 00:55:05 GMT
  6. Organization: Northwest Nexus Inc.
  7. Message-ID: <4dpegi$6ci@news.halcyon.com>
  8. References: <DLE98M.nEI@novice.uwaterloo.ca>
  9. NNTP-Posting-Host: blv-pm10-ip8.halcyon.com
  10. X-Newsreader: Forte Free Agent 1.0.82
  11.  
  12. mkalisia@novice.uwaterloo.ca (Maciej Kalisiak) wrote:
  13.  
  14. >I ran into a "limitation" of C++ that I wasn't aware off, and I was
  15. >hoping someone out there can tell me how to get around this
  16. >limitation:
  17.  
  18. >I have a base class Base. I derive a number of other classes from Base
  19. >using "virtual public". I have an array/list of Base*, which holds
  20. >pointers to a whole bunch of object of type Base, or any of the derived
  21. >ones. I take one of these pointers (Base*) and I know that it was
  22. >really pointing to a derived class. I try to cast to this derived class
  23. >but I can't (supposedly all compilers are supposed to issue an error in
  24. >such a case).
  25.  
  26. >Any ideas of how to keep such a list of derived type objets using
  27. >Base*'s, or how to get around this ???
  28.  
  29. >I am using Watcom v10.0
  30.  
  31. No idea if Watcom 10.0 has run-time type information (RTTI), but the
  32. recent draft(s) of C++ have features for just this kind of problem:
  33.  
  34. dyanmic_cast<Derived1 *>(pBase)
  35.  
  36. The dynamic_cast will return NULL if the instance pointed to by pBase
  37. really isn't of type Derived1, otherwise you get a pointer cast
  38. appropriately.  (Virtual inheritence complicates matters, but
  39. generally you can get where you want by cascading afew dynamic_cast
  40. operations to resovle ambiguities).  
  41.  
  42. This only works on references (or pointers), of course, and only works
  43. if the classes have vtables.  Your polymorphic use of an array of
  44. Base* means you definitely have virtual functions and thus vtables, so
  45. this ought to work for you.
  46.                     --Norm
  47.  
  48.